<template>
  <div class="cus">
    <div class="cus_box" style="width:500px;">
      <div class="title">
        <span>赠送用户套餐</span
        ><i @click="$emit('uploadFile_call')" class="el-icon-close"></i>
      </div>
      <div class="content" style="text-align: center">
        <el-form style="display: flex;justify-content: center;">
          <el-form-item label="赠送的套餐" :label-width="formLabelWidth">
            <el-select
              placeholder="请选择要赠送的套餐"
              :clearable="true"
              v-model="agentValue"
              style="width:250px"
            >
              <el-option
                v-for="item in agentArr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <el-upload
          class="upload-demo"
          ref="uploadBattery"
          :headers="headers"
          :action="action"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :file-list="fileList"
          :auto-upload="false"
          :limit="1"
          :on-exceed="handleExceed"
          :on-change="handleProgress"
        >
          <div style="display: flex;justify-content: center;">
            <el-button
              style="margin-right: 30px;"
              slot="trigger"
              size="small"
              type="primary"
              >选取文件</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传 xlsx 和 xls 格式
            </div>
          </div>
        </el-upload>
      </div>
      <div style="text-align: center" class="mt20">
        <el-button @click="$emit('uploadFile_call', false)">取消</el-button>
        <el-button type="primary" @click="submitUpload">确定</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "uploadFile",
  props: {
    type: [String]
  },
  data() {
    return {
      formLabelWidth: "100px",
      agentValue: "",
      agentArr: [],
      pagination: { limit: 10, offset: 1, total: 1 },
      fileList: [],
      agentForm: {}
    };
  },
  computed: {
    action() {
      return process.env.VUE_APP_URL + "/web/meal/giveMealImport";
    },
    headers() {
      return {
        Authorization: sessionStorage.token
      };
    }
  },
  async mounted() {
    this.agentFn();
  },
  methods: {
    // 拿到套餐列表
    async agentFn() {
      const res = await this.apis.mealList({
        pageNum: 1,
        pageSize: 100,
        name: ""
      });
      const list = res.rows || [];
      this.agentArr = [];
      list.map(res => {
        let options = {
          name: res.name,
          id: res.id
        };
        this.agentArr.push(options);
      });
    },

    //文件上传成功时的钩子
    async handleSuccess(response, file, fileList) {
      //这个方法，再扩展一下 格式和大小限制，没限制的话 可以不加这两个判断
      if (["xlsx", "xls"].indexOf(file.name.split(".")[1]) == -1) {
        //如果是视频格式可以为["video/mp4","video/ogg","video/flv","video/avi","video/wmv","video/rmvb","video/mov"]
        this.$message.error("请上传正确的文件格式");
        return false;
      }
      var fileSize = file.size / 1024 / 1024 < 50; //控制大小 修改50的值即可
      if (!fileSize) {
        this.$message.error("文件大小不能超过50MB");
        return false;
      }

      // const res = await this.apis.mealGiveMealImport({
      //   id: this.agentValue,
      //   file: file.raw
      // });
      let formData = new FormData();
      formData.append("file", file.raw);
      formData.append("id", this.agentValue);
      this.$http({
        url: process.env.VUE_APP_URL + "/web/meal/giveMealImport", //上传文件接口
        method: "post",
        headers: {
          //请求头，根据自身需求加或者不加
          Authorization: sessionStorage.token,
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: formData
      })
        .then(res => {
          console.log(11111111);
          if (res.code == 200) {
            this.$message({
              message: "上传成功",
              type: "success"
            });
          } else if (res.code == 501) {
            this.$message({
              message: res.msg,
              type: "success"
            });
          } else {
            this.$message.error("上传失败");
          }
          this.$emit("uploadFile_call", true, res.data);
        })
        .catch(re => {
          if (re.code == 501) {
            this.$message({
              message: re.msg,
              type: "success"
            });
          } else {
            this.$message.error("上传失败");
          }
          this.$emit("uploadFile_call", true);
        });
    },
    // 确认
    async submitUpload() {
      if (!this.agentValue) {
        return this.$message.error("请选择套餐");
      }
      if (!this.file) {
        return this.$message.error("请选取文件上传");
      }
      // 执行 文件上传成功时的钩子
      this.$refs.uploadBattery.submit();
    },
    //文件上传时的钩子
    handleProgress(file, fileList) {
      this.file = file.raw;
      // console.log('文件上传时的钩子', file, fileList);
      //这个方法，再扩展一下 格式和大小限制，没限制的话 可以不加这两个判断
      if (["xlsx", "xls"].indexOf(file.name.split(".")[1]) == -1) {
        this.$message.error("请上传正确的文件格式");
        return false;
      }
      var fileSize = file.size / 1024 / 1024 < 50; //控制大小 修改50的值即可
      if (!fileSize) {
        this.$message.error("文件大小不能超过50MB");
        return false;
      }
    },
    //文件超出个数限制时的钩子
    handleExceed(file, fileList) {
      // console.log('文件超出个数限制时的钩子', file, fileList);
      this.$message({
        message: "只能上传一个文件",
        type: "error"
      });
    },
    //文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      // console.log('文件列表移除文件时的钩子', file, fileList);
    },
    //点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      // console.log('点击文件列表中已上传的文件时的钩子', file);
    }
  }
};
</script>

<style scoped lang="scss"></style>
